package top.cyuw.simplerpc.util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chen
 * @date 2023/3/16 21:51
 */
public class LockUtil {

    private static final ConcurrentHashMap<String, Lock> locks = new ConcurrentHashMap<>();

    public static void lock(String key) {
        locks.compute(key, (k, lock) -> {
            if (lock == null) {
                lock = new Lock();
            }
            lock.using++;
            return lock;
        }).lock();
    }

    public static void unlock(String key) {
        locks.computeIfPresent(key, (k, lock) -> {
            lock.unlock();
            if (--lock.using == 0) {
                return null;
            } else {
                return lock;
            }
        });
    }

    static class Lock extends ReentrantLock {

        int using;

    }

}